#11:45 - 12:15 

import unittest
import operator as o

translator = {'+':o.add,
		'-':o.sub,
		'*':o.mul,
		'/':o.truediv}
translator.update({str(i):i for i in range(10)})

def make_node(token):
	class Node():
		def __init__(self, ch1, ch2):
			self.ch1 = ch1
			self.ch2 = ch2
		def eval(self):
			return translator[token](self.ch1.eval(), 
					self.ch2.eval())
		def __str__(self):
			return 'Node: '+token

	class Leaf():
		def __init__(self):
			self.value = translator[token]
		def eval(self):
			return self.value
		def __str__(self):
			return 'Leaf: '+token
	
	if token in '*+-/': return Node
	else: return Leaf

def make_tree(string, i=0):
	char = string[i]
	if char in '+-*/': 
		ch1,i = make_tree(string, i+1)
		ch2,i = make_tree(string, i+1)
		node = make_node(char)(ch1, ch2)
		return node, i
	else: 
		return make_node(char)(), i

class TDD(unittest.TestCase):

	def test_translator(self):
		for k,v in translator.items():
			self.assertTrue(type(k)==str)
			if k in '+*-/':
				self.assertTrue(v.__call__ is not None)
	def test_make_leaf(self):
		token = '1'
		self.assertEquals(make_node(token).__name__,'Leaf')
		token = '+'
		self.assertEquals(make_node(token).__name__, 'Node')
	
	def test_make_tree(self):
		tokens = '1'
		root, i = make_tree(tokens)
		self.assertEquals(root.eval(), 1)
		self.assertEquals(i, len(tokens)-1)

		tokens = '+12'
		root, i = make_tree(tokens)
		self.assertEquals(root.eval(), 3)
		self.assertEquals(i, len(tokens)-1)

		tokens = '+2*-53/63'
		root, i = make_tree(tokens)
		self.assertEquals(root.eval(), 6)
		self.assertEquals(i, len(tokens)-1)

unittest.main()
